package com.hzsai.nettylearn.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * hzsai 2019/12/1
 * usage:
 **/
public class MultiplexerTimerServer implements Runnable{

    private static final Logger logger = LoggerFactory.getLogger(MultiplexerTimerServer.class);

    private volatile boolean stop = false;

    private String port;

    private Selector selector;

    private ServerSocketChannel socketChannel;

    public MultiplexerTimerServer(String port) throws IOException {
        this.port = port;
        selector = Selector.open();

        // 创建 channel管道
        socketChannel = ServerSocketChannel.open();
        socketChannel.configureBlocking(false);

        // 将 channel管道事件注册到Selector
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        logger.debug("服务器正常启动，端口【{}】", port);
    }

    private void stop() {
        this.stop = true;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {

        while (true) {

            try {
                selector.select();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
